package com.sunxd.zstudy.designPattern.support.proxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 简单使用jdk proxy 生成代理类并执行方法
 * @author: sun.xd
 * @date: 2021-10-19 14:08
 **/
public class JdkProxy1 {

    public static void main(String[] args) {

//        System.getProperties().put("jdk.proxy.ProxyGenerator.saveGeneratedFiles","true");
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
        Animal o = (Animal) Proxy.newProxyInstance(Dog.class.getClassLoader(), Dog.class.getInterfaces(), new MyHandler(new Dog()));
        o.eat();


    }

    static class MyHandler implements  InvocationHandler{

        private Object object;

        public MyHandler(Object object) {
            this.object = object;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println(proxy.getClass().getName());
            System.out.println("before");
            Object invoke = method.invoke(object, args);
            System.out.println("end");
            return invoke;
        }
    }

    interface Animal{
        void eat();
    }

    static class Dog implements Animal{

        @Override
        public void eat() {
            System.out.println("dog eat");
        }
    }
}
